#!/usr/bin/env python

import os
import wx

class Image(wx.Window):
    '''Image class
    
    @author Julot <andy.julot@gmail.com>
    @since Friday, January 27, 2012. 05:47 PM'''
    
    _image = None
    _path = ''
    _blank = None
    
    def __init__(self, parent):
        wx.Window.__init__(self, parent, style=wx.BORDER_THEME)
        
        self.bitmap = wx.StaticBitmap(self)
        self.Bind(wx.EVT_SIZE, self._onSize)
        self._blank = wx.EmptyBitmap(1 , 1)

    def getPath(self):
        return self._path
    
    def setPath(self, path):
        if not os.path.lexists(path):
            self.clear()
            return
        
        try:
            self._image = wx.Image(path, wx.BITMAP_TYPE_ANY)
            self._path = path
            self._draw()
        except:
            self.clear()
        
    path = property(getPath, setPath)
    
    def _onSize(self, event):
        if self._image: self._draw()
        event.Skip()
        
    def _draw(self):
        '''Draw bitmap
        
        @return boolean whether drawing operation succeeds'''
        
        image = self._image
        if image:
            width, height = image.GetSize()
            if height > self.Size.height or width > self.Size.width:
                # Image needs resizing to fit the parent.
                # Use height as anchor.
                width, height = self.Size
                width = (height * image.Width) / image.Height
                if width > self.Size.width:
                    width, height = self.Size
                    # Width is still wider than the container, switch to width
                    # as anchor.
                    height = (width * image.Height) / image.Width
            image = image.ResampleBicubic(width, height)
            x = (self.Size.width - width) / 2
            y = (self.Size.height - height) / 2
            coord = wx.Point(x, y)
            self.bitmap.SetPosition(coord)
            self.bitmap.SetBitmap(image.ConvertToBitmap())
            self.Refresh()
            return True
        else:
            self.clear()
            return False
    
    def clear(self):
        self._path = ''
        self._image = None
        self.bitmap.SetBitmap(self._blank)
